<?php

namespace App\Http\Controllers\Wechat;

use App\Models\AnswerActivity;
use App\Models\AnswerActivityGift;
use App\Models\AnswerActivityGiftPublic;
use App\Models\AnswerActivityUserPrize;
use App\Validate\AnswerActivityGiftPublicValidate;


/**
 * 活动礼物公示管理
 */
class AnswerActivityGiftPublicController extends CommonController
{

    public $model = null;
    public $validate = null;

    public function __construct()
    {
        parent::__construct();

        $this->model = new AnswerActivityGiftPublic();
        $this->validate = new AnswerActivityGiftPublicValidate();
    }

    /**
     * 列表
     * @param act_id int 活动id
     * @param unit_id int 区域id
     * @param page int 当前页
     * @param limit int 分页大小
     * @param start_time datetime 创建时间范围搜索(开始) 
     * @param end_time datetime 创建时间范围搜索(结束) 
     * @param keywords string 搜索关键词(类型名称)
     */
    public function lists()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('wx_list')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        //判断是否可以添加礼物  或 查询礼物
        $activityGiftModel = new AnswerActivityGift();
        $isAllowAddGift = $activityGiftModel->isAllowAddGift($this->request->act_id);
        if ($isAllowAddGift !== true) {
            return $this->returnApi(202, $isAllowAddGift);
        }

        $page = $this->request->page ? intval($this->request->page) : 1;
        $limit = $this->request->limit ? intval($this->request->limit) : 10;
        $start_time = $this->request->start_time;
        $end_time = $this->request->end_time;
        $keywords = $this->request->keywords;
        $act_id = $this->request->act_id;
        $unit_id = $this->request->unit_id;

        $res = $this->model->lists(null, $act_id, $keywords, $unit_id, $start_time, $end_time, $page, $limit);

        if ($res['total'] == 0 || !$res['data']) {
            return $this->returnApi(203, "管理员暂无投放礼物，请稍后重试！");
        }

        foreach ($res['data'] as $key => $val) {
            $res['data'][$key]['type_name'] = $val['type'] == 1 ?  '文化红包' : '精美礼品';
            $res['data'][$key]['unit_name'] = !empty($val['con_unit']['name']) ?  $val['con_unit']['name'] : config('other.unit_name');

            unset($res['data'][$key]['con_unit']);
        }

         //获取现有抽奖钥匙个数
         $activityUserPrizeModel = new AnswerActivityUserPrize();
         $key_number = $activityUserPrizeModel->getUserPrizeNumber($this->request->act_id , $this->request->token);
         $res['user_info']['key_number'] = empty($key_number) ? 0 : $key_number['number'] - $key_number['use_number'];

        //获取红包和礼物总份数
        $res['total_number'] = $this->model->getTypeTotalNumber($act_id,$unit_id);

        return $this->returnApi(200, "查询成功", true, $res);
    }

   
}
